package com.example.demo.controller;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.client.codec.LongCodec;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.Objects;


/**
 * @author liuyanghui
 */
@RestController
public class Controller {

    @Autowired
    private Redisson redisson;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping(name = "/say", method = RequestMethod.GET)
    String reduceStock() {
        String productId = "productId";
        RLock redissonLock = redisson.getLock(productId);
        try {
            redissonLock.lock();
            int stock = Integer.parseInt(Objects.requireNonNull(stringRedisTemplate.opsForValue().get("key")));
            if (stock > 0) {
                int realStock = stock - 1;
                //更新redis的值
                stringRedisTemplate.opsForValue().set("key", realStock + "");
                System.out.println("扣减库存成功，剩余库存：" + realStock);
                return "success";
            } else {
                System.out.println("库存不足，扣减库存失败");
            }
        }finally {
            redissonLock.unlock();
        }
        return "Hello World!";
    }
}
